//
//  UserOrderController.m
//  SmallElephant
//
//  Created by Faith on 2022/12/24.
//

#import "UserOrderController.h"
#import "UserOrderDetailController.h"
#import "Logistics/UserOrderLogisticsController.h"

@interface UserOrderController () <PHSegmentTabbarDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

/// 搜索组件
@property (nonatomic, strong) UIView *searchView;

/// 分段标签组件
@property (nonatomic, strong) PHSegmentTabbar *segmentTabbar;

/// 列表视图
@property (nonatomic, strong) UICollectionView *listView;

/// 列表数据源
@property (nonatomic, strong) NSMutableArray *listData;

@end

@implementation UserOrderController

- (void)viewDidLoad {
    // 顶部背景占位
    UIView *placeHolderView = [[UIView alloc] init];
    [self.view addSubview:placeHolderView style:@"position: absolute; width: 100%; height: 143px; background: url(bg-my-order@3x);"];
    [super viewDidLoad];
    [self setTitleText:@"我的订单"];
    // 添加搜索组件
    [self.view addSubview:self.searchView style:@"display: flex; flex-direction: row; margin-left: 10px; align-items: center; margin-top: 10px; margin-right: 10px; background: #FFFFFF; border-radius: 20px; height: 40px;"];
    // 添加分段标签组件
    [self.view addSubview:self.segmentTabbar style:@"display: flex; flex-direction: row; margin-top: 15px; margin-left: 10px; margin-right: 10px;"];
    // 添加列表组件
    [self.view addSubview:self.listView style:@"display: flex; flex-grow: 1; align-items: center; margin-top: 5px;"];
    // 加载数据
    [self loadData];
    
}

/// 懒加载搜索组件
- (UIView *)searchView {
    if(!_searchView) {
        // 搜索组件
        _searchView = [[UIView alloc] init];
        
        // 搜索框图标
        UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"magnifyingglass"]];
        searchIcon.tintColor = [UIColor colorWithHexString:@"#999999"];
        [_searchView addSubview:searchIcon style:@"display: flex; width: 20px; height: 20px;  margin-left: 13px;"];
        
        // 搜索输入框
        UITextField *searchInput = [[UITextField alloc] init];
        searchInput.placeholder = @"请输入关键词搜索...";
        searchInput.keyboardType = UIKeyboardTypeNumberPad;
        [_searchView addSubview:searchInput style:@"display: flex; flex:1; color: #666666; font-size: 14px; margin-left: 5px;"];
    }
    return _searchView;
}

/// 懒加载分段Tab 组件
- (PHSegmentTabbar *)segmentTabbar {
    if(!_segmentTabbar) {
        // TAB切换控件
        _segmentTabbar = [[PHSegmentTabbar alloc] init];
        _segmentTabbar.delegate = self;
        [_segmentTabbar setData:@[@"全部", @"待付款", @"待复核", @"待收货", @"已签收", @"退款&售后"]];
    }
    return _segmentTabbar;
}

/// 懒加载数据源
- (NSMutableArray *)listData {
    if(!_listData) {
        _listData = [[NSMutableArray alloc] init];
    }
    return _listData;
}

/// 懒加载列表组件
- (UICollectionView *)listView {
    if(!_listView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumInteritemSpacing = 0; // 每列之间的最小间距
        layout.minimumLineSpacing = SIZE(10); // 每行之间的最小间距
        layout.sectionInset = UIEdgeInsetsMake(SIZE(10), SIZE(10), [UIDevice vg_safeDistanceBottom], SIZE(10)); // 上下左右间距
        layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize;
        _listView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _listView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _listView.backgroundColor = [UIColor clearColor];
        _listView.delegate = self;
        _listView.dataSource = self;
        [_listView registerClass:[UserOrderCell class] forCellWithReuseIdentifier:@"kUserOrderCell"];
    }
    return _listView;
}

/// 单元格数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.listData.count;
}

/// 列表单元视图
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UserOrderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kUserOrderCell" forIndexPath:indexPath];
    [cell setData:self.listData[indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    UserOrderDetailController *controller = [[UserOrderDetailController alloc] init];
    [self pushViewController:controller];
}

- (void)loadData {
    for(int i=0;i<15;i++) {
        [self.listData addObject:@{
            @"platform": @"tm",
            @"createTime": @"2024-11-20 12:11",
            @"title": @"睡不着了啊啊啊啊[苦涩][苦涩][苦涩]吃完外卖喝了两个小啤啤，一点困意都没了[跪了][跪了][跪了] ​",
            @"amount": @(18.23),
            @"number": @(i),
            @"spec": @[@"米白色长袖", @"均码"],
            @"auditRejectReason": i%2==0 ? @"由于平台未为你找到同款商品，无法为您发货" : @"",
            @"cover": @"https://wx1.sinaimg.cn/orj360/002R448Kgy1huwcjn0pllj62c0340u0y02.jpg"
        }];
    }
    [self.listView reloadData];
}

- (void)didSelectIndex:(NSInteger)index {
    
}

@end


/// 列表单元格实现
@interface UserOrderCell()

/// 商品平台图标
@property (nonatomic, strong) UIImageView *platformIcon;

/// 下单时间
@property (nonatomic, strong) UILabel *orderTime;

/// 订单状态
@property (nonatomic, strong) UILabel *orderStatus;

/// 待付款商品图片
@property (nonatomic, strong) UIImageView *coverView;

/// 状态文字
@property (nonatomic, strong) UILabel *statusView;

/// 剩余时间
@property (nonatomic, strong) UILabel *remainTimeView;

/// 订单金额
@property (nonatomic, strong) UILabel *orderAmount;

/// 商品数量
@property (nonatomic, strong) UILabel *productNumber;

/// 复核拒绝原因
@property (nonatomic, strong) UILabel *auditRejectReasonContent;

@end

@implementation UserOrderCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)setupViews {
    
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.cornerRadius = 5;
    self.contentView.layer.masksToBounds = YES;
    
    [self.contentView applyStyle:@"padding: 15px;"];
    
    // 下单时间和订单状态
    UIView *orderTimeAndStatusView = [[UIView alloc] init];
    [self.contentView addSubview:orderTimeAndStatusView style:@"display: flex; flex-direction: row;"];
    // 下单时间
    _orderTime = [[UILabel alloc] init];
    [orderTimeAndStatusView addSubview:_orderTime style:@"display: flex; flex: 1; margin-left: 15px; font-size: 13px; color: #666666;"];
    // 订单状态
    _orderStatus = [[UILabel alloc] init];
    [orderTimeAndStatusView addSubview:_orderStatus style:@"display: flex; font-size: 13px; color: #EF2020;"];
    
    // 订单信息
    UIView *orderInfo = [[UIView alloc] init];
    [self.contentView addSubview:orderInfo style:@"display: flex; flex-direction: row; margin-top: 15px;"];
    // 商品封面
    _coverView = [[UIImageView alloc] init];
    [orderInfo addSubview:_coverView style:@"display: flex; width: 80px; height: 80px; border-radius: 5px;"];
    
    
    // 商品标题和规格
    UIView *infoView = [[UIView alloc] init];
    [orderInfo addSubview:infoView style:@"display: flex; flex: 1; flex-direction: column; margin-left: 8px; "];
    // 商品标题
    _statusView = [[UILabel alloc] init];
    _statusView.numberOfLines = 2;
    [infoView addSubview:_statusView style:@"font-size: 14px; color: #0D0D0D; margin-top: 5px;"];
    // 商品规格
    _remainTimeView = [[UILabel alloc] init];
    [infoView addSubview:_remainTimeView style:@"margin-top: 10px; font-size: 12px; color: #666666;"];
    
    
    // 订单金额和数量
    UIView *orderAmountAndNumber = [[UIView alloc] init];
    [orderInfo addSubview:orderAmountAndNumber style:@"display: flex; flex-direction: column; margin-top: 5px; margin-left: 10px; align-items: flex-end;"];
    
    // 订单金额
    _orderAmount = [[UILabel alloc] init];
    _orderAmount.font = [UIFont systemFontOfSize:FONT_SIZE(12) weight:UIFontWeightBold];
    [orderAmountAndNumber addSubview:_orderAmount style:@"display: flex; color: #333333;"];
    // 商品数量
    _productNumber = [[UILabel alloc] init];
    [orderAmountAndNumber addSubview:_productNumber style:@"display: flex; width: 100%; text-align: right; margin-top: 5px; font-size: 13px; color: #666666;"];
    
    // 复核拒绝原因
    UIView *auditRejectReason = [[UIView alloc] init];
    [self.contentView addSubview:auditRejectReason style:@"display: flex; margin-top: 15px; padding: 10px; border-radius: 5px; background: #FFEFEF"];
    _auditRejectReasonContent = [[UILabel alloc] init];
    _auditRejectReasonContent.numberOfLines = 0;
    [auditRejectReason addSubview:_auditRejectReasonContent style:@"font-size: 13px; color: #EF2020;"];
    
    // 按钮操作组
    UIView *operationButton = [[UIView alloc] init];
    [self.contentView addSubview:operationButton style:@"display: flex; flex-direction: row; margin-top: 15px; justify-content: flex-end;"];
    
    UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnCancel setTitle:@"取消订单" forState:UIControlStateNormal];
    [operationButton addSubview:btnCancel style:@"display: flex; height: 30px; margin-right:10px; padding-left:10px; padding-right: 10px; border-radius: 5px; font-size: 13px; color: #333333; border-width: 1px; border-color: #CECECE;"];
    
    UIButton *btnModify = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnModify setTitle:@"修改订单" forState:UIControlStateNormal];
    [operationButton addSubview:btnModify style:@"display: flex; height: 30px; margin-right:10px; padding-left:10px; padding-right: 10px; border-radius: 5px; font-size: 13px; color: #333333; border-width: 1px; border-color: #CECECE;"];
    
    UIButton *btnPay = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnPay addTarget:self action:@selector(btnPayClicEventHandler:) forControlEvents:UIControlEventTouchUpInside];
    [btnPay setTitle:@"去支付" forState:UIControlStateNormal];
    [operationButton addSubview:btnPay style:@"display: flex; height: 30px; padding-left:10px; padding-right: 10px; border-radius: 5px; font-size: 13px; color: #EF2020; align-self: center; border-width: 1px; border-color: #EF2020;"];
    
    // 商品平台
    _platformIcon = [[UIImageView alloc] init];
    [self.contentView addSubview:_platformIcon style:@"position: absolute; width: 38px; height: 38px;"];
    
}

- (CGSize)sizeThatFits:(CGSize)size {
    [self.contentView configureLayoutWithBlock:^(YGLayout * _Nonnull layout) {
        layout.isEnabled = true;
        layout.flexDirection = YGFlexDirectionColumn;
        layout.width = YGPointValue(SCREEN_WIDTH - SIZE(21));
    }];
    [self.contentView.yoga applyLayoutPreservingOrigin:YES dimensionFlexibility:YGDimensionFlexibilityFlexibleHeight];
    return [self.contentView sizeThatFits:size];
}

- (void)setData:(NSDictionary *)data {
    [self.platformIcon setImage:[UIImage imageWithName:@"icon-order-taobao@3x"]];
    [self.coverView setImageUrl:data[@"cover"]];
    self.orderTime.text = [NSString stringWithFormat:@"下单时间: %@", data[@"createTime"]];
    self.orderStatus.text = @"请耐心等待平台复核";
    self.statusView.text = [NSString stringWithFormat:@"%@", data[@"title"]];
    self.remainTimeView.text = [data[@"spec"] componentsJoinedByString:@", "];
    // 格式化价格
    NSString *orderAmountString = [NSString stringWithFormat:@"%.2f", [data[@"amount"] floatValue]];
    NSRange dotRange = [orderAmountString rangeOfString:@"."];
    NSMutableAttributedString *orderAmountAttributeString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"¥%@", orderAmountString]];
    [orderAmountAttributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:FONT_SIZE(18)] range:NSMakeRange(1, dotRange.location)];
    self.orderAmount.attributedText = orderAmountAttributeString;
    // 设置数量
    self.productNumber.text = [NSString stringWithFormat:@"共%@件", data[@"number"]];
    // 复核拒绝原因
    NSString *auditRejectReasonText = [NSString stringWithFormat:@"%@", data[@"auditRejectReason"]];
    if(auditRejectReasonText.length==0) {
        [self.auditRejectReasonContent.superview applyStyle:@"display: none;"];
        self.auditRejectReasonContent.text = @"";
    } else {
        [self.auditRejectReasonContent.superview applyStyle:@"display: flex;"];
        self.auditRejectReasonContent.text = [NSString stringWithFormat:@"复核拒绝理由：%@", auditRejectReasonText];
    }
}

- (void)btnPayClicEventHandler:(UIButton*)button {
    UserOrderLogisticsController *controller = [[UserOrderLogisticsController alloc] init];
    [[self getRootController] pushViewController:controller];
}

@end
